package com.efounder.chat.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.efounder.chat.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * Created by long on 2017/2/9.
 */

public class GPSUtils {

    private static final String TAG = "GPSUtils";
    private static LocationManager lm;
    private static Context mContext;

    //step 1 注册GPS定位信息
    public static void registerGPS(Context context,GPSCallBack gspCallBack){
        mContext = context;
        mGPSCallBack = gspCallBack;
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //判断GPS是否正常启动
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(context, R.string.wrchatview_gps, Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
//            context.startActivityForResult(intent, 0);
//            finish();
            return;
        }
        //为获取地理位置信息时设置查询条件
        String bestProvider = lm.getBestProvider(getCriteria(), true);
        //获取位置信息
        //如果不设置查询要求，getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
        Location location = lm.getLastKnownLocation(bestProvider);
        mGPSCallBack.updateView(location);
        listener = initStateListner();
        //监听状态
        lm.addGpsStatusListener(listener);
        //绑定监听，有4个参数
        //参数1，设备：有GPS_PROVIDER和NETWORK_PROVIDER两种
        //参数2，位置信息更新周期，单位毫秒
        //参数3，位置变化最小距离：当位置距离变化超过此值时，将更新位置信息
        //参数4，监听
        //备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新

        // 1秒更新一次，或最小位移变化超过1米更新一次；
        //注意：此处更新准确度非常低，推荐在service里面启动一个Thread，在run中sleep(10000);然后执行handler.sendMessage(),更新位置
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return;
        }
        locationListener = initLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, locationListener);
    }

    //Step2 注销GPS 信息
    public static void unRegisterGPS(){
        lm.removeUpdates(locationListener);
        locationListener = null;
        listener = null;
        lm = null;
        mContext = null;
        mGPSCallBack = null;
    }


    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //位置监听
    private static LocationListener locationListener;
    private static LocationListener initLocationListener(){
        return new LocationListener() {
            /**
             * 位置信息变化时触发
             */
            public void onLocationChanged(Location location) {
                mGPSCallBack.updateView(location);
                try {
                    Log.i(TAG, "时间：" + longToDate(location.getTime(),"yyyy-MM-dd HH:mm:ss"));
                    Date date = new Date(location.getTime());
                    Log.i(TAG,"时间1："+dateFormat.format(date));
//                tvContent.setText(dateFormat.format(date));
                    String dateStr = dateFormat.format(date);
                    Log.i("lcusky","---date:"+DateUtils.dateToLong(dateStr.split(" ")[1]));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "经度：" + location.getLongitude());
                Log.i(TAG, "纬度：" + location.getLatitude());
                Log.i(TAG, "海拔：" + location.getAltitude());
            }
            public  Date longToDate(long currentTime, String formatType)
                    throws ParseException {
                Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
                String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
                Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
                return date;
            }
            public  Date stringToDate(String strTime, String formatType)
                    throws ParseException {
                SimpleDateFormat formatter = new SimpleDateFormat(formatType);
                Date date = null;
                date = formatter.parse(strTime);
                return date;
            }
            public  String dateToString(Date data, String formatType) {
                return new SimpleDateFormat(formatType).format(data);
            }
            /**
             * GPS状态变化时触发
             */
            public void onStatusChanged(String provider, int status, Bundle extras) {
                switch (status) {
                    //GPS状态为可见时
                    case LocationProvider.AVAILABLE:
                        Log.i(TAG, "当前GPS状态为可见状态");
                        break;
                    //GPS状态为服务区外时
                    case LocationProvider.OUT_OF_SERVICE:
                        Log.i(TAG, "当前GPS状态为服务区外状态");
                        break;
                    //GPS状态为暂停服务时
                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        Log.i(TAG, "当前GPS状态为暂停服务状态");
                        break;
                }
            }

            /**
             * GPS开启时触发
             */
            public void onProviderEnabled(String provider) {
                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                Location location = lm.getLastKnownLocation(provider);
                mGPSCallBack.updateView(location);
            }
            /**
             * GPS禁用时触发
             */
            public void onProviderDisabled(String provider) {
                mGPSCallBack.updateView(null);
            }
        };
    }

    //状态监听
   private static GpsStatus.Listener listener ;

    private static GpsStatus.Listener initStateListner(){
        return new GpsStatus.Listener() {
            public void onGpsStatusChanged(int event) {
                switch (event) {
                    //第一次定位
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        Log.i(TAG, "第一次定位");
                        break;
                    //卫星状态改变
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
//                    Log.i(TAG, "卫星状态改变");
                        //获取当前状态
                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        GpsStatus gpsStatus = lm.getGpsStatus(null);
                        //获取卫星颗数的默认最大值
                        int maxSatellites = gpsStatus.getMaxSatellites();
                        //创建一个迭代器保存所有卫星
                        Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                        int count = 0;
                        while (iters.hasNext() && count <= maxSatellites) {
                            GpsSatellite s = iters.next();
                            count++;
                        }
                        System.out.println("搜索到："+count+"颗卫星");
                        break;
                    //定位启动
                    case GpsStatus.GPS_EVENT_STARTED:
                        Log.i(TAG, "定位启动");
                        break;
                    //定位结束
                    case GpsStatus.GPS_EVENT_STOPPED:
                        Log.i(TAG, "定位结束");
                        break;
                }
            };
        };
    }
    /**
     * 返回查询条件
     * @return
     */
    private static Criteria getCriteria(){
        Criteria criteria=new Criteria();
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }

    /**判断非空*/
    public interface GPSCallBack{
        public void updateView(Location location);
    }

    private static GPSCallBack mGPSCallBack;
}

